package com.ysy.acl;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.server.auth.DigestAuthenticationProvider;

import java.util.ArrayList;
import java.util.List;

/**
 * @program: zookeeper-demo
 * @description: Client 通过调用addAuthInfo()函数设置当前会话的Author信息（针对Digest 验证模式）
 * @author: yeshiyuan
 * @create: 2019-06-18 11:13
 **/
public class NewDigest {

    public static void main(String[] args) throws Exception {//new一个acl
        List<ACL> acls = new ArrayList<ACL>();
        //添加第一个id，采用用户名密码形式
        Id id1 = new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin"));
        ACL acl1 = new ACL(ZooDefs.Perms.ALL, id1);
        acls.add(acl1);
        //添加第二个id，所有用户可读权限
       /* Id id2 = new Id("world", "anyone");
        ACL acl2 = new ACL(ZooDefs.Perms.READ, id2);
        acls.add(acl2);*/
        //添加第二个id，指定ip可读权限
        Id id3 = new Id("ip", "172.24.24.43");
        ACL acl3 = new ACL(ZooDefs.Perms.READ, id3);
        acls.add(acl3);
        // Zk用admin认证，创建/test ZNode。
        ZooKeeper Zk = new ZooKeeper("192.168.5.35:2181",20000, null);
        Zk.addAuthInfo("digest", "admin:admin".getBytes());
        Stat stat = Zk.exists("/test", null);
        if (stat == null) {
            Zk.create("/test", "data".getBytes(), acls, CreateMode.PERSISTENT);
        }
        Zk.setData("/test", "有权限".getBytes(), -1);
        try {
            //zk写拦截
            ZooKeeper writeZk = new ZooKeeper("192.168.5.35:2181", 20000, null);
            writeZk.setData("/test", "asdasd".getBytes(), -1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            //zk读请求(ip acl测试)
            ZooKeeper readZk = new ZooKeeper("192.168.5.35:2181", 20000, null);
            byte[] bytes = readZk.getData("/test", null, null);
            System.out.println("read data:" + new String(bytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}
